"""
API路由模块
组织和管理所有API端点
"""
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import List, Optional
from app.core.qa_chain import qa_chain_system
from app.core.recommendation import recommendation_system
from app.core.cache import cache_manager
from app.utils.document_processor import DocumentProcessor
from app.schemas.schemas import (
    QueryModel, RecommendationModel, DocumentProcessModel, 
    ProgressUpdateModel, QuestionAnswerResponse, LearningPathResponse
)

# 创建API路由器
router = APIRouter()

# 导入文档路由
from app.api.document_routes import router as document_router

# 包含文档路由
router.include_router(document_router)

class QueryModel(BaseModel):
    question: str
    user_id: str

class RecommendationModel(BaseModel):
    user_id: str
    subject: str

class DocumentProcessModel(BaseModel):
    file_path: str
    file_type: str  # "text" or "pdf"
    use_mineru_pages: Optional[List[int]] = None

class ProgressUpdateModel(BaseModel):
    user_id: str
    subject: str
    progress: float  # 0-1之间的数值

@router.get("/")
async def root():
    return {"message": "欢迎使用AI教育助手API"}

@router.post("/query", response_model=QuestionAnswerResponse)
async def query_knowledge(query: QueryModel):
    """处理知识问答请求"""
    try:
        # 检查短期缓存中是否有相关回答
        cached_answer = cache_manager.get_short_term_cache(f"qa:{query.user_id}:{query.question}")
        if cached_answer:
            return cached_answer
        
        # 生成新的回答
        answer = qa_chain_system.answer_question(query.question, query.user_id)
        
        # 缓存回答（短期）
        cache_manager.set_short_term_cache(f"qa:{query.user_id}:{query.question}", answer)
        
        return answer
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理问答时出错: {str(e)}")

@router.post("/recommend", response_model=LearningPathResponse)
async def recommend_learning_path(recommendation: RecommendationModel):
    """生成个性化学习路径推荐"""
    try:
        learning_path = recommendation_system.generate_learning_path(
            recommendation.user_id, 
            recommendation.subject
        )
        
        return {
            "user_id": recommendation.user_id, 
            "subject": recommendation.subject,
            "learning_path": learning_path
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成学习路径时出错: {str(e)}")

@router.post("/process_document")
async def process_document(doc_info: DocumentProcessModel):
    """处理文档"""
    try:
        processor = DocumentProcessor()
        
        if doc_info.file_type == "text":
            content = processor.process_text_document(doc_info.file_path)
            return {"content": content, "type": "text", "status": "success"}
        elif doc_info.file_type == "pdf":
            result = processor.process_pdf_document(
                doc_info.file_path, 
                doc_info.use_mineru_pages
            )
            return {"result": result, "type": "pdf", "status": "success"}
        else:
            raise HTTPException(status_code=400, detail="不支持的文件类型")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理文档时出错: {str(e)}")

@router.post("/update_progress")
async def update_progress(progress: ProgressUpdateModel):
    """更新学习进度"""
    try:
        success = recommendation_system.update_user_progress(
            progress.user_id,
            progress.subject,
            progress.progress
        )
        
        if success:
            return {"message": "学习进度更新成功"}
        else:
            raise HTTPException(status_code=500, detail="学习进度更新失败")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新学习进度时出错: {str(e)}")